/*
 * @Author: your name
 * @Date: 2022-03-31 14:43:40
 * @LastEditTime: 2022-04-11 18:11:18
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \mallAdmin\src\app\main\used-store\used-order-manage\used-order-branch\used-order-branch.component.ts
 */
import { Component, OnInit } from '@angular/core';
import { DatePipe } from '@angular/common';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';

import { UsedStoreZservice } from '../../used-store-zservice';
import { orderSplitAccountStates, orderStateArrs } from '../../used-store-manage.pipe';
import { PermissionService } from '../../../../service/permission.service';

@Component({
  selector: 'app-used-order-branch',
  templateUrl: './used-order-branch.component.html',
  styleUrls: ['./used-order-branch.component.scss'],
  providers: [DatePipe]
})
export class UsedOrderBranchComponent implements OnInit {

  isCollapse: boolean = true;
  searchParams: any = {
    orderNum: '', // 订单号
    supplierId: '', // 货主(供应商)
    payType: '', // 付款方式
    status: '', // 订单状态
    createTime: '', // 下单开始时间
    endTime: '', // 下单结束时间
    beginPayTime: '', // 付款开始时间
    endPayTime: '', // 付款结束时间
    beginShipTime: '', // 发货开始时间
    endShipTime: '', // 发货结束时间
    receiptTime: '', // 收货开始时间
    receiptEndTime: '', // 收货结束时间
    separateTime: '', // 分账开始时间
    separateEndTime: '', // 分账结束时间
    separateStatus: '', // 分账状态
    separateNo: '' // 分账流水单号
  };
  splitAccountOptions: any = [...orderSplitAccountStates]; // 分账状态options

  orderStateOptions: any = [...orderStateArrs]; // 订单状态options
  stateSelected: any = []; // 订单状态Options Selected

  // 下单时间
  creatDates: any = [];
  // 付款时间
  payDates: any = [];
  // 发货时间
  shipDates: any = [];
  // 收货时间
  receiptDates: any = [];
  // 分账时间
  separateDates: any = [];

  // 货主options（供应商）
  supplierOptions: any = [];
  supplierSelected: any = [];

  tableParams: any = {
    tableData: [],
    loading: false,
    page: 1,
    pageSize: 20,
    total: 0
  };
  // 合计
  tableRowSum: any = {};

  /**
   * 分账 Modal
   * ----------------------------------------------------------------
   */
  isVisible: boolean = false;
  submitLoading: boolean = false;
  validateForm!: FormGroup;
  modalItem: any = null;

  constructor(
    private datePipe: DatePipe,
    private fb: FormBuilder,
    private modal: NzModalService,
    private message: NzMessageService,
    private services: UsedStoreZservice,
    public permission: PermissionService
  ) { }

  ngOnInit(): void {
    this.validateForm = this.fb.group({
      amount: ['', [Validators.required]]
    });

    this.querySupplierOptions();
    this.loadTable();
  }

  // 查询货主
  async querySupplierOptions() {
    let params = {
      page: 1,
      pageSize: 9999
    }
    const res: any = await this.services.querySupplierList(params);
    if (res.code === 0) {
      const { records } = res.data || {};
      this.supplierOptions = records.filter((item: any) => item.name) || [];
    } else {
      this.message.error(res.message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.querySplitAccountList(params);
    this.tableParams.loading = false;
    
    if (res.code === 0) {
      const { list, sum } = res?.data?.data || {};
      this.tableParams.tableData = list?.records || [];
      this.tableParams.total = list?.total || 0;
      this.tableRowSum = sum || {};
    } else {
      this.message.error(res.message);
    }
  }

  queryData() {
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData() {
    for (let key in this.searchParams) {
      this.searchParams[key] = '';
    }
    this.creatDates= [];
    this.payDates = [];
    this.shipDates = [];
    this.receiptDates = [];
    this.separateDates = [];
    this.stateSelected = [];
    this.supplierSelected = [];

    this.tableParams.page = 1;
    this.loadTable();
  }

  timeChange(result: any, [startTime, endTime]: Array<any>) {
    this.searchParams[startTime] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd') : '';
    this.searchParams[endTime] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd') : '';
  }

  multipleSelectChange(result: any, keyStr: string) {
    this.searchParams[keyStr] = result.join(',');
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    // this.loadTable();
  }
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    // this.loadTable();
  }

  // days ago
  returnDaysAgo(time: string) {
    let oneDay = 1000 * 60 * 60 * 24;
    let startTimeStamp = new Date(time).getTime() + oneDay;
    let endTimeStamp = Date.now();
    let diffVal: any = (endTimeStamp - startTimeStamp) / (1000 * 60 * 60 * 24);

    return diffVal && parseInt(diffVal) > 0 ? parseInt(diffVal) : 0;
  }

  /**
   * ----------------------------------------------------------------
   * 分账 Modal
   * ----------------------------------------------------------------
   */
  returnAccountAmount(item: any) {
    // 实收总额 * （1 - 服务费） * (1 - 6‰) = 分账金额
    let resultAmount = 0;
    resultAmount = (item.realPrice || 0) * (1 - (item.serviceFee || 0) / 100) * (1 - 0.006);
    return resultAmount.toFixed(2) || 0;
  }

  showAccountModal(item: any) {
    this.validateForm.reset();
    this.validateForm.get('amount')?.setValue(this.returnAccountAmount(item));
    this.modalItem = item || {};
    this.isVisible = true;
  }

  submitAccount() {
    if (this.validateForm.valid) {
      // console.log('submit', this.validateForm.value);
      this.submitInterface();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({ onlySelf: true });
        }
      });
    }
  }

  submitInterface() {
    let amountVal = this.returnAccountAmount(this.modalItem);
    let inputVal = this.validateForm.get('amount')?.value;
    
    this.modal.confirm({
      nzTitle: '提示',
      nzContent: `${Number(amountVal) !== Number(inputVal) ? '分账金额和计算结果不一致，' : ''}确定分账？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          orderId: this.modalItem.id, // 订单ID
          supplierId: this.modalItem.supplierId, // 供应商ID
          separateMoney: this.validateForm.get('amount')?.value // 分账金额
        }
        this.submitLoading = true;
        const res: any = await this.services.updateSeparateItem(params);
        this.submitLoading = false;
        
        if (res.code === 0) {
          this.isVisible = false;
          this.message.success('操作成功');
          this.loadTable();
        } else {
          this.message.error(res.message || '操作失败');
        }
      },
      nzCancelText: '取消'
    });
  }

  // 撤回分账
  withdrawAccount(item: any) {
    // console.log('withdraw Account', item);
    this.modal.confirm({
      nzTitle: '撤回分账',
      nzContent: `已分账：<b>${ item.separateAmount }</b> 元，确认撤回？`,
      nzOkText: '确认',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let params = {
          id: item.id
        }
        const res: any = await this.services.revokeSeparateItem(params);
        if (res.code === 0) {
          this.message.success('操作成功');
          this.loadTable();
        } else {
          this.message.error(res.message || '操作失败');
        }
      },
      nzCancelText: '取消'
    });
  }
}
